package util

import (
	"d-serv-go/server/core/bean"
	"regexp"
	"strings"
)

var BeanUtil = newBeanUtil()

type beanUtil struct {
}

func newBeanUtil() *beanUtil {
	return &beanUtil{}
}

var KEY_PATTERN = "(?i)#((\\w|_|[\u4e00-\u9fa5])*)#"

func (u *beanUtil) ReplaceValues(src string, dateBean *bean.Bean) string {
	reg, _ := regexp.Compile(KEY_PATTERN) //不区分大小写
	for _, s := range reg.FindAllStringSubmatch(src, -1) {
		src = strings.ReplaceAll(src, s[0], dateBean.GetStr(s[1]))
	}
	return src
}

func (u *beanUtil) GetListByMatch(match *bean.Bean, list []*bean.Bean, maxSize int) []*bean.Bean {
	_list := make([]*bean.Bean, 0)
	for _, bean := range list {
		m := true
		for _, key := range match.Keys() {
			if match.Get(key) != nil && match.Get(key) != bean.Get(key) {
				m = false
				break
			}
		}
		if m {
			_list = append(_list, bean)
		}
		if len(_list) >= maxSize {
			break
		}
	}
	return _list
}

func (u *beanUtil) MergeBean(oldBean *bean.Bean, newBean *bean.Bean) *bean.Bean {
	var mergeBean *bean.Bean
	if oldBean != nil {
		mergeBean = oldBean.Clone()
		trans(newBean, mergeBean, nil) //传递新值
	} else {
		mergeBean = newBean.Clone()
	}
	return mergeBean
}

func trans(src, tar *bean.Bean, keys []string) {
	if keys != nil {
		for _, key := range keys {
			tar.Set(key, src.Get(key))
		}
	} else {
		tar.SetMap(src.GetMap())
	}
}
